package com.lswms.modules.lswms.service.impl.orders;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.modules.lswms.dao.orders.OrderallocationDao;
import com.lswms.modules.lswms.dto.orders.OrderallocationDTO;
import com.lswms.modules.lswms.entity.orders.OrderallocationEntity;
import com.lswms.modules.lswms.entity.orders.OrderdetailEntity;
import com.lswms.modules.lswms.service.orders.OrderallocationService;

/**
 * 分配的订单
 *
 * @author DX sunlightcs@gmail.com
 * @since 1.0.0 2021-07-04
 */
@Service
public class OrderallocationServiceImpl extends CrudServiceImpl<OrderallocationDao, OrderallocationEntity, OrderallocationDTO> implements OrderallocationService {

    @Override
    public QueryWrapper<OrderallocationEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String orderkey = (String)params.get("orderkey");

        QueryWrapper<OrderallocationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(orderkey), "orderkey", orderkey);
        wrapper.orderByDesc("orderkey");
        
        return wrapper;
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addOrderList(List<OrderdetailEntity> orderList) {

		for (OrderdetailEntity orderdetailEntity : orderList) {
			QueryWrapper<OrderallocationEntity> orderallocationEntityQuery = new QueryWrapper<OrderallocationEntity>();
			orderallocationEntityQuery.eq("orderkey", orderdetailEntity.getOrderkey()) ;
			
			Integer count= baseDao.selectCount(orderallocationEntityQuery);
			if(count==0) {
				OrderallocationEntity orderallocationEntity = new OrderallocationEntity();
				orderallocationEntity.setOrderkey(orderdetailEntity.getOrderkey());
				baseDao.insert(orderallocationEntity);
			}
		}
		
	}

	
	@Transactional(rollbackFor = Exception.class)
	public void delete(List<OrderdetailEntity> orderList) {
//		for (OrderdetailEntity orderdetailEntity : orderList) {
//			QueryWrapper<OrderallocationEntity> orderallocationEntityQuery = new QueryWrapper<OrderallocationEntity>();
//			orderallocationEntityQuery.eq("orderkey", orderdetailEntity.getOrderkey()) ;
//			baseDao.delete(orderallocationEntityQuery);
//		}
		
		QueryWrapper<OrderallocationEntity> orderallocationEntityQuery = new QueryWrapper<OrderallocationEntity>();
		orderallocationEntityQuery.in("orderkey", orderList.stream().map(item->item.getOrderkey()).collect(Collectors.toList())) ;
		baseDao.delete(orderallocationEntityQuery);
	}

}